package com.zxkj.ssm.weixin.shop.http.executor;
import com.zxkj.ssm.weixin.shop.exception.WxErrorException;
import com.zxkj.ssm.weixin.shop.handler.Utf8ResponseHandler;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;

/**
 *@Author cxy
 *@Date 2018/7/11 9:10
 *@Description 简单的GET请求执行器，请求的参数是String, 返回的结果也是String
 *@Version
 */
public class SimpleGetRequestExecutor implements RequestExecutor<String, String> {
  @Override
  public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String url, String queryParam) throws WxErrorException, IOException {
    if (queryParam != null) {
      if (url.indexOf('?') == -1) {
        url += '?';
      }
      url += url.endsWith("?") ? queryParam : '&' + queryParam;
      }
      HttpGet httpGet = new HttpGet(url);
      if (httpProxy != null) {
        RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
        httpGet.setConfig(config);
      }
      try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
          return Utf8ResponseHandler.INSTANCE.handleResponse(response);
      } finally {
        httpGet.releaseConnection();
      }
     }

}
